package dhz.storage.dao;

import dhz.storage.models.ShareLink;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.SortOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.desktop.QuitResponse;
import java.util.List;

@Service
public class ShareLinkDaoImpl implements ShareLinkDao{
    @Resource
    MongoTemplate template;

    @Override
    public long save(ShareLink s_link){
        return template.save(s_link).getId();
    }

    @Override
    public boolean remove(long target){
        Query rm_query = new Query();
        Criteria c = Criteria.where("id").is(target);
        rm_query.addCriteria(c);
        return template.remove(rm_query, ShareLink.class).getDeletedCount() == 1L;
    }

    @Override
    public boolean exist(long target) {
        Query exist_query = new Query();
        Criteria c = Criteria.where("id").is(target);
        exist_query.addCriteria(c);
        return template.exists(exist_query, ShareLink.class);
    }

    @Override
    public long countLinks(String identification) {
        Query count_link_query = new Query();
        Criteria c = Criteria.where("identification").is(identification);
        count_link_query.addCriteria(c);
        return template.count(count_link_query, ShareLink.class);
    }

    @Override
    public List<ShareLink> findShareLinks(String identification, int page) {
        Query findLinks = new Query();
        Criteria c = Criteria.where("identification").is(identification);
        findLinks.addCriteria(c);
        findLinks.skip((page-1)* 10L).limit(10).with(Sort.by(Sort.Direction.DESC, "creation"));
        return template.find(findLinks, ShareLink.class);
    }

    @Override
    public ShareLink getLink(long id) {
        Query getOne = new Query();
        Criteria c = Criteria.where("id").is(id);
        getOne.addCriteria(c);
        return template.findOne(getOne,ShareLink.class);
    }
}
